package com.cy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.security.Provider;
import java.util.Map;

@RestController
@RequestMapping("/consumer/")
public class RestConsumerController {
    @Autowired
    private RestTemplate loadBalancedRestTemplate;

    @DeleteMapping("{id}")
    public String doDeleteByid(@PathVariable String id) {
//        String url1 ="http://nacos-Provider/provider/"+id;
        String url = String.format("http://%s/provider/%s", "nacos-provider", id);
        System.out.println(url);
//        loadBalancedRestTemplate.delete(url,id);
//        return "delete ok";
//        假如需要获取服务提供方，执行的删除操作的结果，可以通过如下方式进行实现
        ResponseEntity<String> exchange = loadBalancedRestTemplate.exchange(
                url, //请求URL
                HttpMethod.DELETE,//请求方式
                null,//请求实体参数
                String.class);//响应数据的类型
        return exchange.getBody();
    }

//   添加操作
    @PostMapping
    public Map<String, Object> doCreate(@RequestBody Map<String, Object> request) {
        //....后续要将请求数据写入到数据库System.out.println("consumer.map="+map);
        String url = String.format("http://%s/provider/", "nacos-provider");
        return loadBalancedRestTemplate.postForObject(url, request, Map.class);
        // return "create ok";
    }
//    @PostMapping
//    public String doCreate1(@RequestBody Map<String,Object> map){
//        //....后续要将请求数据写入到数据库
//         String url1 = String.format("http://%s/provider/", "nacos-provider");
//         return  loadBalancedRestTemplate.postForObject(url1,map,String.class);
//
//    }
    @PutMapping
    public Map<String,Object> doUpdate(@RequestBody Map<String, Object> request) {
        //....后续要将请求数据写入到数据库System.out.println("consumer.map="+map);
        String url = String.format("http://%s/provider/", "nacos-provider");
//        loadBalancedRestTemplate.put(url,request);
        //假如希望获取服务提供方执行更新操作时的响应结果，可以采用如下方式
        HttpEntity httpEntity=new HttpEntity(request);
        ResponseEntity<Map> exchange = loadBalancedRestTemplate.exchange(
                url,//请求url
                HttpMethod.PUT,//请求方式
                httpEntity, //请求实体
                Map.class);//响应数据类型
        return exchange.getBody();
        // return "create ok";
    }
}


